package com.boarsoft.message.adapter;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.boarsoft.common.util.StreamUtil;
import com.boarsoft.message.bean.Message;
import com.boarsoft.message.core.MessageService;
import com.boarsoft.serialize.JavaSerializer;
import com.boarsoft.serialize.ObjectSerializer;

/**
 * 基于HTTP协议发送Message对象到远程消息服务
 * 
 * @author Mac_J
 *
 */
public class HttpMessageClient implements MessageService {
	/** */
	protected String url;
	/** */
	protected int connectTimeout = 3000;
	/** */
	protected int readTimeout = 30000;
	/** */
	protected ObjectSerializer serializer = new JavaSerializer();

	@Override
	public void put(Message m) throws Exception {
		byte[] ba = serializer.serialize(m);
		//
		BufferedOutputStream bos = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;
		try {
			conn = (HttpURLConnection) new URL(url).openConnection();
			conn.setConnectTimeout(3000);
			conn.setReadTimeout(30000);
			conn.setRequestProperty("User-Agent", "Mozilla/5.0");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/octet-stream");
			conn.setRequestProperty("Content-Length", String.valueOf(ba.length));
			//
			bos = new BufferedOutputStream(conn.getOutputStream());
			// for (int off = 0; off < ba.length; off += 2048) {
			// bos.write(ba, off, Math.min(ba.length - off, 2048));
			// }
			bos.write(ba);
			bos.flush();
			//
			int status = conn.getResponseCode();
			if (status != 200) {
				throw new InternalError(conn.getResponseMessage());
			}
		} finally {
			StreamUtil.close(br);
			StreamUtil.close(bos);
			if (conn != null) {
				conn.disconnect();
			}
		}
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public int getConnectTimeout() {
		return connectTimeout;
	}

	public void setConnectTimeout(int connectTimeout) {
		this.connectTimeout = connectTimeout;
	}

	public int getReadTimeout() {
		return readTimeout;
	}

	public void setReadTimeout(int readTimeout) {
		this.readTimeout = readTimeout;
	}

	public ObjectSerializer getSerializer() {
		return serializer;
	}

	public void setSerializer(ObjectSerializer serializer) {
		this.serializer = serializer;
	}
}
